#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int T;
  for (cin >> T; T; T--) {
    int n, m;

    cin >> n >> m;
    vector<vector<int>> a(n, vector<int>(m));

    int maxa = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
        maxa = max(maxa, a[i][j]);
      }
    }

    vector<int> cnt_row(n, 0), cnt_col(m, 0);

    int ans = maxa, tot = 0;

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (a[i][j] == maxa) {
          cnt_row[i]++;
          cnt_col[j]++;
          tot++;
        }
      }
    }

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (cnt_row[i] + cnt_col[j] - (a[i][j] == maxa) == tot) {
          ans = maxa - 1;
        }
      }
    }
    cout << ans << "\n";
  }
  return 0;
}